package nz.ac.massey.doi_information_extractor.database;

import java.sql.SQLException;
import java.util.ArrayList;

import nz.ac.massey.doi_information_extractor.data.Author;
import nz.ac.massey.doi_information_extractor.data.Publication;

/**
 * Mock database used for testing of other classes while the database is under development
 *
 */
public class MockDatabase implements DatabaseInterface{

	private ArrayList<Publication> publicationList;
	private ArrayList<Author> authorList;
	private int authorIdCounter;
	private int publicationIdCounter;

	public MockDatabase(){
		publicationList = new ArrayList<Publication>();
		authorList = new ArrayList<Author>();
		authorIdCounter = 0;
		publicationIdCounter = 0;
	}

	@Override
	public Publication read(String doi) {
		for(int index = 0; index < publicationList.size(); index++){
			if(publicationList.get(index).getDoi().equals(doi))
				return publicationList.get(index);
		}
		return null;
	}

	@Override
	public void write(Publication publication) throws SQLException {
		if(publication == null)
			return;

		if(publication.getPublicationId() == -1){
			publication.setPublicationId(publicationIdCounter++);
			publicationList.add(publication);
			return;
		}

		for(int index = 0; index < publicationList.size(); index++){
			if(publicationList.get(index).equals(publication)){
				publicationList.set(index,publication);
				return;
			}
		}
	}

	@Override
	public String[] getDoiList() {
		String[] doiList = new String[publicationList.size()];

		for(int index = 0; index < publicationList.size(); index++){
			doiList[index] = publicationList.get(index).getDoi();
		}
		return doiList;
	}



	@Override
	public void delete(String doi) throws SQLException {
		for(int index = 0; index < publicationList.size(); index++){
			if(publicationList.get(index).getDoi().equals(doi)){
				publicationList.remove(index);
				return;
			}
		}
	}

	@Override
	public ArrayList<Author> getAuthors() throws SQLException {
		return authorList;
	}

	@Override
	public void writeAuthor(Author author) {
		if(author == null)
			return;

		if(author.getAuthorId() == -1){
			author.setAuthorId(authorIdCounter++);
			authorList.add(author);
		}

		for(int index = 0; index < authorList.size();index++){
			if(authorList.get(index).equals(author)){
				authorList.set(index, author);
				return;
			}
		}
	}

	@Override
	public void closeConnection() {
	}
}
